<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="车辆编码" prop="vehiclesCode">
        <el-input v-model="queryParams.vehiclesCode" placeholder="请输入车辆编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="服务部门" prop="deptId">
        <el-select v-model="queryParams.deptId" placeholder="请选择员服务部门" clearable>
          <el-option v-for="optVal in deptOptions" :key="optVal.deptId" :label="optVal.deptName" :value="optVal.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="车牌号码" prop="vehiclesNumber">
        <el-input v-model="queryParams.vehiclesNumber" placeholder="请输入车牌号码" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['erecord:vehicles:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['erecord:vehicles:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['erecord:vehicles:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['erecord:vehicles:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="vehiclesList" @selection-change="handleSelectionChange" @row-click="handleDetail" >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" label="序号" width="55">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="id" align="center" prop="id" v-if="false" />
      <el-table-column label="车辆编码" align="center" prop="vehiclesCode" v-if="true" width="100"/>
      <el-table-column label="服务部门" align="center" prop="deptName" width="110"/>
      <el-table-column label="服务类型" align="center" prop="serviceType" width="110">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.erecord_service_type" :value="scope.row.serviceType" />
        </template>
      </el-table-column>
      <el-table-column label="车辆设备名称" align="center" prop="vehiclesName" width="110"/>
      <el-table-column label="车辆类型" align="center" prop="vehiclesType" />
      <el-table-column label="车牌号码" align="center" prop="vehiclesNumber" width="100"/>
      <el-table-column label="品牌" align="center" prop="brand" width="100"/>
      <el-table-column label="规格型号" align="center" prop="specificationMode" />
      <el-table-column label="车辆注册日期" align="center" prop="registerDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.registerDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="纯电动" align="center" prop="evFlag">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.evFlag" />
        </template>
      </el-table-column>
      <el-table-column label="总质量（KG）" align="center" prop="totalWeight" />
      <el-table-column label="是否加装GPS" align="center" prop="gpsFlag">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.gpsFlag" />
        </template>
      </el-table-column>
      <el-table-column label="车辆行驶证编号" align="center" prop="vehicleLicenseNo" width="120"/>
      <el-table-column label="驾驶员" align="center" prop="employeeName" />
      <el-table-column label="手机号码" align="center" prop="phone" width="120"/>
      <el-table-column label="准驾车型" align="center" prop="drivingVehiclesType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.erecord_driving_vehicles_type" :value="scope.row.drivingVehiclesType" />
        </template>
      </el-table-column>
      <el-table-column label="保险期限" align="center" prop="insureDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.insureDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="驾驶证有效期" align="center" prop="drivingLicenseValidityDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.drivingLicenseValidityDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="行驶证有效期" align="center" prop="travelLicenseValidityDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.travelLicenseValidityDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="驾驶证照片" align="center" prop="drivingLicensePic" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.drivingLicensePicUrl" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="行驶证照片" align="center" prop="travelLicensePic" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.travelLicensePicUrl" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="正前面照片" align="center" prop="frontPic" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.frontPicUrl" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="正侧面照片" align="center" prop="sidePic" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.sidePicUrl" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="正后面照片" align="center" prop="behindPic" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.behindPicUrl" :width="50" :height="50" />
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" align="center" prop="updateBy" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['erecord:vehicles:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['erecord:vehicles:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改车辆对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" :disabled="isDetail">

        <div style="margin: 0px 0px 20px;">
          <label style="font-size: 20px;">基本信息</label>
        </div>

        <el-row>
          <el-col :span="12">
            <el-form-item label="车辆编码" prop="vehiclesCode">
              <el-input v-model="form.vehiclesCode" placeholder="请输入车辆编码" :readonly="!isAdd"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务部门" prop="deptId">
              <el-select v-model="form.deptId" placeholder="请选择员服务部门" clearable>
                <el-option v-for="optVal in deptOptions" :key="optVal.deptId" :label="optVal.deptName"
                  :value="optVal.deptId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="服务类型" prop="serviceType">
              <el-select v-model="form.serviceType" placeholder="请选择服务类型">
                <el-option v-for="dict in dict.type.erecord_service_type" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆设备名称" prop="vehiclesName">
              <el-input v-model="form.vehiclesName" placeholder="请输入车辆设备名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="车辆类型" prop="vehiclesType">
              <el-input v-model="form.vehiclesType" placeholder="请输入车辆类型" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车牌号码" prop="vehiclesNumber">
              <el-input v-model="form.vehiclesNumber" placeholder="请输入车牌号码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specificationMode">
              <el-input v-model="form.specificationMode" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="车辆注册日期" prop="registerDate">
              <el-date-picker clearable v-model="form.registerDate" type="date" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择车辆注册日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纯电动" prop="evFlag">
              <el-select v-model="form.evFlag" placeholder="请选择纯电动">
                <el-option v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="总质量（KG）" prop="totalWeight">
              <el-input v-model="form.totalWeight" placeholder="请输入总质量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否加装GPS" prop="gpsFlag">
              <el-select v-model="form.gpsFlag" placeholder="请选择是否加装GPS">
                <el-option v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="车辆行驶证编号" prop="vehicleLicenseNo">
              <el-input v-model="form.vehicleLicenseNo" placeholder="请输入车辆行驶证编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="驾驶员" prop="employeeCode">
              <!--
              <el-select v-model="form.employeeCode" :multiple-limit="1" filterable remote reserve-keyword placeholder="请输入驾驶员"
                :remote-method="getEmpUserByName" :loading="loading">
                <el-option v-for="item in userNameOptions" :key="item.employeeCode" :label="item.employeeName"
                  :value="item.employeeCode" >
                </el-option>
              </el-select>
              -->
              <el-autocomplete class="inline-input" v-model="form.employeeName" :fetch-suggestions="getEmpUserByName"
                placeholder="请输入内容" @select="handleNameSelect" :debounce="0"></el-autocomplete>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="准驾车型" prop="drivingVehiclesType">
              <el-select v-model="form.drivingVehiclesType" placeholder="请选择准驾车型">
                <el-option v-for="dict in dict.type.erecord_driving_vehicles_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="保险期限" prop="insureDate">
              <el-date-picker clearable v-model="form.insureDate" type="date" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择保险期限">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="驾驶证有效期" prop="drivingLicenseValidityDate">
              <el-date-picker clearable v-model="form.drivingLicenseValidityDate" type="date"
                value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择驾驶证有效期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="行驶证有效期" prop="travelLicenseValidityDate">
              <el-date-picker clearable v-model="form.travelLicenseValidityDate" type="date"
                value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择行驶证有效期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" maxlength="500" show-word-limit />
          </el-form-item>
        </el-row>

        <div style="margin: 20px 0px 20px;">
          <label style="font-size: 20px;">扩展信息</label>
        </div>

        <el-row>
          <el-col :span="12">
            <el-form-item label="驾驶证照片" prop="drivingLicensePic">
              <image-upload v-model="form.drivingLicensePic" :limit="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="行驶证照片" prop="travelLicensePic">
              <image-upload v-model="form.travelLicensePic" :limit="1" />
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="正前面照片" prop="frontPic">
              <image-upload v-model="form.frontPic" :limit="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="正侧面照片" prop="sidePic">
              <image-upload v-model="form.sidePic" :limit="1" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="正后面照片" prop="behindPic">
              <image-upload v-model="form.behindPic" :limit="1" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer" v-show="!isDetail">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVehicles, getVehicles, delVehicles, addVehicles, updateVehicles } from "@/api/erecord/vehicles";
import { getDeptAndPost, getEmpUserByName } from "@/api/erecord/common";

export default {
  name: "Vehicles",
  dicts: ['erecord_service_type', 'sys_yes_no', 'erecord_driving_vehicles_type'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      showTis: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车辆表格数据
      vehiclesList: [],
      // 部门树选项
      deptOptions: undefined,
      userNameOptions: [],
      // 弹出层标题
      title: "",
      // 是否新增
      isAdd: true,
      // 是否显示弹出层
      open: false,
      isDetail: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        vehiclesCode: undefined,
        deptId: undefined,
        vehiclesNumber: undefined,
        orderByColumn: "update_time,vehiclesCode",
        isAsc: "desc,asc",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        vehiclesCode: [
          { required: true, message: "车辆编码不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "服务部门不能为空", trigger: "blur" }
        ],
        vehiclesName: [
          { required: true, message: "车辆设备名称不能为空", trigger: "blur" }
        ],
        vehiclesType: [
          { required: true, message: "车辆类型不能为空", trigger: "blur" }
        ],
        vehiclesNumber: [
          { required: true, message: "车牌号码不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDeptAndPost();
  },
  methods: {
    /** 查询车辆列表 */
    getList() {
      this.loading = true;
      listVehicles(this.queryParams).then(response => {
        this.vehiclesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptAndPost() {
      getDeptAndPost("queryPost=false").then(response => {
        this.deptOptions = response.data.depts;
        // this.postOptions = response.data.posts;
      });
    },
    getEmpUserByName(queryString, cb) {
      cb([])
      //this.loading = true;
      getEmpUserByName(queryString).then(response => {
        this.userNameOptions = [...response.data];
        // this.loading = false;
        console.log("------- user name list : ", this.userNameOptions)
        const result = this.userNameOptions.map(x => ({ ...x, value: x.employeeName }))
        if (result.length == '0') {
          result.push({
            employeeCode: '-1',
            value: '无匹配结果'
          })
        }
        cb(result)
      });
    },
    handleNameSelect(item) {
      console.log('handleNameSelect -- ', item)
      if (item.employeeCode === '-1') return;
      this.form.employeeCode = item.id;
      this.form.employeeName = item.employeeName;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        vehiclesCode: undefined,
        deptId: undefined,
        serviceType: undefined,
        vehiclesName: undefined,
        vehiclesType: undefined,
        vehiclesNumber: undefined,
        brand: undefined,
        specificationMode: undefined,
        registerDate: undefined,
        evFlag: undefined,
        totalWeight: undefined,
        gpsFlag: undefined,
        vehicleLicenseNo: undefined,
        employeeCode: undefined,
        phone: undefined,
        drivingVehiclesType: undefined,
        insureDate: undefined,
        drivingLicenseValidityDate: undefined,
        travelLicenseValidityDate: undefined,
        drivingLicensePic: undefined,
        travelLicensePic: undefined,
        frontPic: undefined,
        sidePic: undefined,
        behindPic: undefined,
        remark: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined,
        delFlag: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.showTis = selection.map(item => item.vehiclesCode)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isAdd = true;
      this.isDetail = false;
      this.title = "添加车辆";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const vehiclesCode = row.id || this.ids
      getVehicles(vehiclesCode).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.isDetail = false;
        this.isAdd = false;
        this.title = "修改车辆";
      });
    },
    handleDetail(row) {
      this.loading = true;
      this.isAdd = false;
      this.isDetail = true;
      this.reset();
      const employeeCode = row.id || this.ids
      getVehicles(employeeCode).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "查看车辆";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.isAdd == false) {
            updateVehicles(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addVehicles(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const vehiclesCodes = row.id || this.ids;
      this.$modal.confirm('是否确认删除数据').then(() => {
        this.loading = true;
        return delVehicles(vehiclesCodes);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('erecord/vehicles/export', {
        ...this.queryParams
      }, `车辆列表${this.parseTime(new Date().getTime(), '{y}{m}{d}')}.xlsx`)
    }
  }
};
</script>
